package com.tensquare.spit.service;

import com.tensquare.spit.dao.SpitDao;
import com.tensquare.spit.pojo.Spit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.test.context.junit4.statements.SpringFailOnTimeout;
import util.IdWorker;

import java.util.Date;
import java.util.List;

@Service
public class SpitService {

    @Autowired
    private SpitDao spitDao;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private MongoTemplate mongoTemplate;

    public List<Spit> findAll(){
        return spitDao.findAll();
    }

    public Spit findById(String id){
        return spitDao.findById(id).get();
    }

    public void save(Spit spit){
        spit.set_id(idWorker.nextId()+"");
        spit.setPublishtime(new Date());//发布日期
        spit.setVisits(0);//浏览量
        spit.setShare(0);//分享数
        spit.setThumbup(0);//点赞数
        spit.setComment(0);//回复数
        spit.setState("1");//状态
        spitDao.save(spit);

        if(spit.getParentid()!=null&&!"".equals(spit.getParentid())){
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").is(spit.getParentid())); //{_id: id}
            Update update = new Update();
            update.inc("comment", 1);
            mongoTemplate.upsert(query, update, Spit.class);
        }
    }

    public void update(Spit spit){
        spitDao.save(spit);
    }

    public void delete(String id){
        spitDao.deleteById(id);
    }

    //根据上级ID查询吐槽列表（分页）
    public Page<Spit> findByParentid(String id, int page, int size){
        Pageable pageable = PageRequest.of(page - 1, size); // 0,2
        Page<Spit> page1 = spitDao.findByParentid(id, pageable);
        return page1;
    }

    //吐槽点赞
    public void updateThumbup(String id){

        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id)); //{_id: id}
        Update update = new Update();
        update.inc("thumbup", 1);
        mongoTemplate.upsert(query, update, Spit.class);

    }
}
